package com.lc.afbx.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lc.afbx.BaseApplication;
import com.lc.afbx.R;
import com.lc.afbx.RequestManager;
import com.lc.afbx.adapters.MyAdapter;
import com.lc.afbx.conn.GetApiIndexIndex;
import com.lc.afbx.util.PrefrenceConfig;
import com.module.pull.PullToRefreshBase;
import com.module.pull.PullToRefreshListView;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.bound.BoundViewHelper;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.pager.Carousel;
import com.zcx.helper.util.UtilToast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2016/3/14.
 */
public class NavigationActivity extends BaseActivity implements View.OnClickListener {

    @BoundView(R.id.convenientBanner) private ConvenientBanner convenientBanner;
    @BoundView(R.id.navigation_lv) private PullToRefreshListView pullToRefreshListView;
    @BoundView(R.id.area_shi_tv) private TextView area_shi_tv;
    private ListView navigation_lv;

    private MyAdapter adapter;

    private List<GetApiIndexIndex.New> news = new ArrayList<>();

    private boolean isLogin;//用户登录状态

    private GetApiIndexIndex getApiIndexIndex = new GetApiIndexIndex(new AsyCallBack<GetApiIndexIndex.Info>() {

        @Override
        public void onSuccess(String toast, int type, GetApiIndexIndex.Info info) throws Exception {

            news.addAll(info.news);

            adapter.notifyDataSetChanged();

            convenientBanner.setPages(
                    new CBViewHolderCreator<LocalImageHolderView>() {
                        @Override
                        public LocalImageHolderView createHolder() {
                            return new LocalImageHolderView();
                        }
                    }, info.datas).setPageIndicator(new int[]{R.drawable.shape_yuanxing_no_sel_bg, R.drawable.shape_yuanxing_sel_bg})
                    //设置指示器的方向
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                    .startTurning(3000)
                    .setCanLoop(true);


        }

        @Override
        public void onFail(String toast, int type) throws Exception {

            UtilToast.show(context, toast);

        }

        @Override
        public void onEnd(String toast, int type) throws Exception {

            pullToRefreshListView.onPullDownRefreshComplete();

            setLastUpdateTime();//设置最后刷新时间

        }
    });


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation);

        //header
        View view = BoundViewHelper.boundView(this, BaseApplication.ScaleScreenHelper.loadView((ViewGroup) getLayoutInflater().inflate(R.layout.inflate_activity_home_jz, null)));

        pullToRefreshListView.setScrollLoadEnabled(false);
        pullToRefreshListView.setPullLoadEnabled(false);
        pullToRefreshListView.setPullRefreshEnabled(true);

        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                news.clear();
                getApiIndexIndex.execute(context, false);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                pullToRefreshListView.onPullUpRefreshComplete();
            }
        });

        navigation_lv = pullToRefreshListView.getRefreshableView();

        //加头
        navigation_lv.addHeaderView(view, null, false);
        navigation_lv.setDivider(null);
        navigation_lv.setVerticalScrollBarEnabled(false);

        navigation_lv.setAdapter(adapter = new MyAdapter(NavigationActivity.this, news));

        //listview监听
        navigation_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(context, NewsDetailsActivity.class);
                intent.putExtra("id", news.get(position - 1).id);
                intent.putExtra("title", news.get(position - 1).title);
                startActivity(intent);
            }
        });

        pullToRefreshListView.doPullRefreshing(true, 500);
        setLastUpdateTime();

        area_shi_tv.setText(BaseApplication.BasePreferences.readHomeCityName());

        findViewById(R.id.more_news_tv).setOnClickListener(this);

    }


    //    点击事件
    @Override
    public void onClick(View view) {


        switch (view.getId()) {

            case R.id.shouye_img_geren:

                startActivity(new Intent(this, PersonalCenterActivity.class));

                break;

            case R.id.shouye_img_hezuogongsi:

                startActivity(new Intent(this, CooperationCompanyActivity.class));

                break;

            case R.id.shouye_img_tuijianyoujingxi:

                startActivity(new Intent(this, SurperiseActivity.class));

                break;

            case R.id.shouye_img_shangjiaruzhu:

                if (isLogin) {

                    startActivity(new Intent(this, BusinessJoinActivity.class));

                } else {

                    startActivity(new Intent(this, LoginActivity.class));
                    return;
                }


                break;

            case R.id.shouye_img_jiamengjigou:

                startActivity(new Intent(this, JoinOrganizationActivity.class));

                break;

            case R.id.shouye_layout_jiaoqiangxian:

                if (isLogin) {

                    startActivity(new Intent(this, CompulsoryInsuranceActivity.class));

                } else {

                    startActivity(new Intent(this, LoginActivity.class));

                    return;

                }


                break;

            case R.id.shouye_layout_shangyexian:

                if (isLogin) {

                    startActivity(new Intent(this, BusinessInsuranceActivity.class));

                } else {

                    startActivity(new Intent(this, LoginActivity.class));
                    return;

                }


                break;

            case R.id.shouye_layout_yiwaixian:

                if (isLogin) {

                    startActivity(new Intent(this, AccidentInsuranceActivity.class));

                } else {

                    startActivity(new Intent(this, LoginActivity.class));

                    return;
                }


                break;

            case R.id.shouye_layout_shouxian:

                if (isLogin) {

                    startActivity(new Intent(this, LifeInsuranceActivity.class));

                } else {

                    startActivity(new Intent(this, LoginActivity.class));

                    return;
                }


                break;

            case R.id.shouye_layout_weizhangchaxun:

                startActivity(new Intent(this, QueryViolationActivity.class));

                break;

            case R.id.shouye_layout_lipeichaxun:

                startActivity(new Intent(this, InsuranceSearchActivity.class));

                break;

            case R.id.shouye_layout_weiquanzixun:

                startActivity(new Intent(this, ConsultationActivity.class));


                break;

            case R.id.more_news_tv:

                startActivity(new Intent(this, MoreNewsActivity.class));

                break;

            case R.id.shouye_tilte:

                //这个值随便了，穿下个activity就是检测空不空
                startActivityForResult(new Intent(this, ChoseAreaActivity.class).putExtra(PrefrenceConfig.INTENT_TAG, "city"), 3);

                return;

        }



    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

//        UtilLog.e("看看","这个方法走没走啊");
        switch (resultCode) {

            case 3:

                Bundle bundle = data.getExtras();

                ArrayList list = bundle.getParcelableArrayList("list");

                List<Map<String, String>> lists = (List<Map<String, String>>) list.get(0);

                BaseApplication.BasePreferences.saveHomeCityName(lists.get(1).get("title"));
                BaseApplication.BasePreferences.saveHomeCityID(lists.get(1).get("id"));

                area_shi_tv.setText(lists.get(1).get("title"));

                break;

            default:
                break;
        }
    }


    @Override
    protected void onResume() {
        isLogin = BaseApplication.BasePreferences.readIsLogin();//这个是退出时 所有数据清空，这个页面不会销毁 重建，登陆状态刷新
        super.onResume();
    }

    public class LocalImageHolderView implements Holder<GetApiIndexIndex.Data> {
        private SimpleDraweeView imageView;
        private View view;

        @Override
        public View createView(Context context) {

            view = LayoutInflater.from(context).inflate(R.layout.banner_item, null, false);

            imageView = (SimpleDraweeView) view.findViewById(R.id.banner_item_iv);

            return view;
        }

        @Override
        public void UpdateUI(final Context context, final int position, final GetApiIndexIndex.Data data) {
            imageView.setImageURI(Uri.parse(data.picurl));

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    startActivity(new Intent(context, BannerDetailActivity.class).putExtra("bannerId", data.id));

                }
            });
        }


    }


    private void setLastUpdateTime() {
        String text = formatDateTime(System.currentTimeMillis());
        pullToRefreshListView.setLastUpdatedLabel(text);
    }

    private String formatDateTime(long time) {
        if (0 == time) {
            return "";
        }

        SimpleDateFormat mDateFormat = new SimpleDateFormat("HH:mm:ss");
        return mDateFormat.format(new Date(time));
    }

}
